package com.abysshal.icarte.datamodel.util;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.util.Date;

import com.abysshal.icarte.datamodel.net.Packet;
import com.abysshal.icarte.datamodel.obj.Menu;
import com.abysshal.icarte.datamodel.obj.Order;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GSonTools {
	private static final Gson gsonSerializer = new GsonBuilder().
		registerTypeAdapter(java.util.Date.class, new UtilDateSerializer()).setDateFormat(DateFormat.LONG).create();  
	
	private static final Gson gsonDeserializer = new GsonBuilder().
		registerTypeAdapter(java.util.Date.class, new UtilDateDeserializer()).setDateFormat(DateFormat.LONG).create(); 
	/** 
     * Serializer
     * @param bean 
     * @param type 
     * @return 
     */  
    public static String bean2json(Object bean, Type type) {  
        return gsonSerializer.toJson(bean);  
    }  
  
    /** 
     * Deserializer 
     * @param json 
     * @param type 
     * @return 
     */  
    public static <T> T json2bean(String json, Type type) {           
        return gsonDeserializer.fromJson(json, type);  
    }  
    
    public static void main(String args[]){
    	Menu m = new Menu();
    	m.setDescription("Menu 1 desc\n Another line");
    	m.setId(1l);
    	m.setName("Menu 1 Name");
    	m.setOnsale(true);
    	m.setOrigPic("http://localhost/origpic.png");
    	m.setRank(4);
    	m.setStartSaleTime(new Date());
    	m.setThumbPic("https://localhost:8080/thumbpic.png");
    	String mjson = GSonTools.bean2json(m, null);
    	System.out.println(mjson);
    	
    	Menu m2 = GSonTools.json2bean(mjson, Menu.class);
    	System.out.println(m.getDescription() + m.getStartSaleTime().getTime());
    	
    	Order order = new Order();
    	order.setCreateTime(new Date());
    	order.setDesknum(2);
    	order.setId(313l);
    	order.setTotalCost(10099);
    	order.setUpdateTime(new Date());
    	order.add(m.getId(), 3);
    	order.add(2l, 1);
    	String ojson = GSonTools.bean2json(order, Order.class);
    	System.out.println(ojson);
    	
    	Order order2 = GSonTools.json2bean(ojson, Order.class);
    	System.out.println(order.getMenus().get(m.getId()) + " " + order.getMenus().get(2l));
    	
    	Packet p = new Packet();
    	p.setTime(new Date());
    	p.setAction("GETVERSION");
    	p.setContent("");
    	System.out.println(GSonTools.bean2json(p, Packet.class));
    }
}
